package com.hopedove.callsystem.activity.call

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.core.widget.doOnTextChanged
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hopedove.base.BaseActivity
import com.hopedove.callsystem.R
import com.hopedove.callsystem.constant.TICKET_NO
import com.hopedove.callsystem.databinding.BacktrayActivityLayoutBinding
import com.hopedove.callsystem.domain.net.CallBackTray
import com.hopedove.callsystem.domain.net.GetWhlocByMachine
import com.hopedove.net.ErrResponse
import com.hopedove.net.OkResponse
import com.hopedove.net.domain.Communication
import com.hopedove.utils.ToastUtil
import com.hopedove.view.SimpleDialog
import com.hopedove.view.TipsDialogFragment
import com.hoperun.callsystem.adapter.CarAdapter
import com.hoperun.callsystem.entity.CarEntity
import org.json.JSONObject

/**
 *退托盘呼叫
 */
class BackTrayCallActivity : BaseActivity() {
    private lateinit var mAdapter: CarAdapter
    var mCarList: List<CarEntity>? = null
    var mMacineNo = ""
    var mClothTktNo = ""
    var mMateriaInfo = ""

    lateinit var binding: BacktrayActivityLayoutBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = BacktrayActivityLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initViewAndEvent()
    }


    private fun initViewAndEvent() {
        mAdapter = CarAdapter(3)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            mAdapter.setCurrent(position)
        }
        binding.recyclerview.adapter = mAdapter
        mClothTktNo = intent?.getStringExtra("clothTktNo").toString()
        mMacineNo = if (mClothTktNo.length > 4) {
            mClothTktNo.substring(0, 4)
        } else ""
        intent?.getStringExtra("materiaInfo")?.let { mMateriaInfo = it }
        mCarList = intent?.getSerializableExtra("dataList")?.let { it as List<CarEntity> }
        if (mCarList != null && mCarList?.size!! > 0) {
            mAdapter.setNewData(mCarList)
            binding.inputEt.setText(mMacineNo)
            binding.inputEt.isFocusable = false
        }
        binding.inputEt.setOnKeyListener(object : View.OnKeyListener {
            override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
                if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                    getWhlocByMachine()
                    return true
                }
                return false
            }

        })
        binding.inputEt.imeOptions = EditorInfo.IME_ACTION_SEARCH;
        binding.inputEt.doOnTextChanged { text, start, count, after ->
            mAdapter.setNewData(null)
            mAdapter.setCurrent(-1)
        }
        binding.callBtn.setOnClickListener {
            startCall()
        }
    }

    private fun startCall() {
        if (mAdapter.selection == -1) {
            ToastUtil.longToast(this, "请选择后再呼叫！")
            return
        }
        showWait()
        val whlocoNo = (mAdapter.data[mAdapter.selection] as CarEntity).WHLOCNO
        val machineNo = binding.inputEt.text.toString()

        Communication.asyncRequest(CallBackTray(whlocoNo, machineNo)) { r ->
            stopWait()
            if (r is OkResponse) {
                //SimpleDialog.show(this, msg)
                val view = layoutInflater.inflate(R.layout.callsys_tips_type_2, null)
                val tipDialog = TipsDialogFragment.newInstance(view)
                tipDialog.isCancelable = false
                tipDialog.show(supportFragmentManager, "tipDialog")
                Handler().postDelayed({
                    tipDialog.dismiss()
                    goMaterial()
                    this.finish()
                }, 3000)
            } else if (r is ErrResponse) {
                SimpleDialog.show(this, "检验呼叫失败！")
            }
        }

    }


    /**
     * 根据车号带出库位信息
     */
    private fun getWhlocByMachine() {
        val machineNo = binding.inputEt.text.toString()
        if (machineNo.isEmpty()) {
            SimpleDialog.show(this, "请输入条码后再确认！")
            return
        }
        showWait()

        Communication.asyncRequest(GetWhlocByMachine(machineNo)) { r ->
            stopWait()
            if (r is OkResponse) {
                val jsonObj = JSONObject(r.data)
                val data = jsonObj.optJSONArray("DATALIST")
                val carList = Gson().fromJson<List<CarEntity>>(
                    data?.toString(),
                    object : TypeToken<List<CarEntity>>() {}.type
                )
                mAdapter.setCurrent(-1)
                mAdapter.setNewData(carList)
            } else if (r is ErrResponse) {
                SimpleDialog.show(this, "获取库位失败！")
            }
        }

    }


    private fun goMaterial() {
        if (mMateriaInfo.isEmpty()) {
            return
        }
        val intent = Intent(this, MaterialInfoActivity::class.java)
        intent.putExtra(TICKET_NO, binding.inputEt.text.toString())
        intent.putExtra(ScanBarcodeActivity.SOURCE_DATA, mMateriaInfo)
        startActivity(intent)
    }

}